<?php

namespace app\admin\service;

use app\model\ConsultOfflineModel;
use app\model\ConsultOfflineResultModel;
use app\model\ConsultOfflineTaskModel;
use app\model\ConsultOnlineMessageModel;
use app\model\ConsultOnlineModel;
use app\model\ConsultOnlineResultModel;
use app\model\CrisisMeasuresModel;
use app\model\CrisisTypeModel;
use app\model\DepartmentLevelModel;
use app\model\DepartmentModel;
use app\model\FollowUserModel;
use app\model\InterfereUserModel;
use app\model\ProxyEvaluationResultModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskUserResultModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpWord\Exception\CopyFileException;
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Service;

class InterfereExportService extends Service
{

    /**
     * oss上传
     * @param $path
     * @param $ext
     * @param $save_name
     * @return mixed
     */
    public function oss($path, $ext, $save_name): mixed
    {
        // 上传单文件
        $upload = new \app\common\Upload();
        // 设置上传类型和文件大小
        $upload = $upload->defaultConfig();
        $fileContent = file_get_contents($path);
        return $upload->upload($fileContent, 'binary', $ext, $save_name);
    }

    /**
     * 批量导出关注人群
     * @param array $ids 列表id
     * @param int $unit_id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function FollowUserExport(array $ids, int $unit_id): string
    {
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 设置工作表标题
        $sheet->setTitle('关注人群');
        // 设置单元格数据
        $sheet->setCellValue('A1', '名称');
        $sheet->setCellValue('B1', '性别');
        $sheet->setCellValue('C1', '年龄');
        $sheet->setCellValue('D1', '所在部门');
        $sheet->setCellValue('E1', '编号');
        $sheet->setCellValue('F1', '关注等级');
        $sheet->setCellValue('G1', '关注负责人');
        $sheet->setCellValue('H1', '正在第几次跟进');
        $sheet->setCellValue('I1', '测评报告等级');
        $sheet->setCellValue('J1', '发现途径');
        $sheet->setCellValue('K1', '测评量表和结果');
        $sheet->setCellValue('L1', '允许查报告权限');
        $sheet->setCellValue('M1', '加入关注时间');
        $sheet->setCellValue('N1', '测评量表分类');
        $sheet->setCellValue('O1', '测评总分');
        $sheet->setCellValue('P1', '申请报告解读');
        $sheet->setCellValue('Q1', '所在单位');
//        $sheet->setCellValue('R1', '学籍状态');
        $sheet->setCellValue('R1', '注册账号');
        $sheet->setCellValue('S1', '测评用户类型');
        $sheet->setCellValue('T1', '所在部门管理员');
        $FollowUserModel = new FollowUserModel();
        $data = $FollowUserModel->where('id', 'in', $ids)
            ->with([
                'operator',
                'user' => function ($query) {
                    $query->with(['unitName']);
                }
            ])->select()->toArray();
        if (count($data) > 0) {
            $department_id = array_column($data, 'department_id');
            $UserService = new UserService($this->app);
            $admin = $UserService->getDepartmentAdminAll($department_id);
            $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
            foreach ($data as $key => $item) {
                switch ($item['channel']) {
                    case 2:
                        $TaskUserResultModel = new TaskUserResultModel();
                        $result = $TaskUserResultModel->with([
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['channel_id']);
                        break;
                    case 3:
                        $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                        $result = $SelfEvaluationResultModel->with([
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['channel_id']);
                        break;
                    case 4:
                        $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
                        $result = $ProxyEvaluationResultModel->with([
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['channel_id']);
                        break;
                    case 6:
                        $ConsultOnlineResultModel = new ConsultOnlineResultModel();
                        $result = $ConsultOnlineResultModel->with([
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['channel_id']);
                        break;
                    case 7:
                        $ConsultOfflineResultModel = new ConsultOfflineResultModel();
                        $result = $ConsultOfflineResultModel->with([
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['channel_id']);
                        break;
                }
                $item['rating_scale_name'] = $result['rating_scale_name'] ?? '';
                $item['warning_name'] = $result['warning_name'] ?? '';
                $item['result_read_auth'] = $result['result_read_auth'] ?? '';
                $item['total_score'] = $result['total_score'] ?? '';
                $item['is_explain'] = $result['is_explain'] ?? '';
                $item['rating_scale_type_name'] = $result['rating_scale_type_name'] ?? '';
                $item['answer_role'] = $result['answer_role'] ?? '';
                //关注等级
                $item['level_name'] = match ($item['level']) {
                    1 => '轻度',
                    2 => '中度',
                    3 => '重度',
                    4 => '密切',
                    default => '--',
                };
                /**
                 * 来源渠道【1危机上报手动移入，2,任务测评自动加入，3自我测评自动加入，4他人代测自动移入，5无线测评自动移入，6线上咨询手动移入，7线下预约手动移入，8关注人群手动导入，9干预人群手动导入】
                 */
                $item['channel_name'] = match ($item['channel']) {
                    1 => '危机上报手动移入',
                    2 => '任务测评自动加入',
                    3 => '自我测评自动加入',
                    4 => '他人代测自动移入',
                    5 => '无线测评自动移入',
                    6 => '线上咨询手动移入',
                    7 => '线下预约手动移入',
                    8 => '关注人群手动导入',
                    9 => '干预人群手动导入',
                    default => '--',
                };
                $item['explain_name'] = match ($item['is_explain']) {
                    1 => '未解读',
                    2 => '申请中',
                    3 => '已解读',
                    default => '--',
                };
                $item['student_name'] = match ($item['student_status']) {
                    1 => '在读',
                    2 => '已毕业',
                    3 => '已退学',
                    4 => '休学',
                    default => '--',
                };
                if (!empty($item['result_read_auth'])) {
                    $result_read_auth = explode(',', $item['result_read_auth']);
                    $auth_name = '';
                    foreach ($result_read_auth as $v) {
                        $auth_name .= match ($v) {
                                '1' => '管理员',
                                '2' => '咨询师',
                                '3' => '用户',
                                '4' => '家长',
                                default => '',
                            } . '、';
                    }
                    $auth_name = rtrim($auth_name);
                } else {
                    $auth_name = '--';
                }
                // 设置单元格数据
                $key = $key + 2;
                $sheet->setCellValue('A' . $key, $item['user_name']);
                $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                $sheet->setCellValue('C' . $key, $item['user_age'] ?: '--');
                $sheet->setCellValue('D' . $key, $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '--');
                $sheet->setCellValue('E' . $key, $item['user_number'] ?: '--');
                $sheet->setCellValue('F' . $key, $item['level_name']);
                $sheet->setCellValue('G' . $key, $item['operator_name']);
                $sheet->setCellValue('H' . $key, $item['up_num']);
                $sheet->setCellValue('I' . $key, $item['warning_name']);
                $sheet->setCellValue('J' . $key, $item['channel_name']);
                $sheet->setCellValue('K' . $key, $item['rating_scale_name']);
                $sheet->setCellValue('L' . $key, $auth_name);
                $sheet->setCellValue('M' . $key, date('Y-m-d H:i:s', $item['time']));
                $sheet->setCellValue('N' . $key, $item['rating_scale_type_name']);
                $sheet->setCellValue('O' . $key, $item['total_score']);
                $sheet->setCellValue('P' . $key, $item['explain_name']);
                $sheet->setCellValue('Q' . $key, $item['unit_name']);
//                $sheet->setCellValue('R' . $key, $item['student_name']);
                $sheet->setCellValue('R' . $key, $item['username'].' ');
                $sheet->setCellValue('S' . $key, $item['answer_role'] == 1 ? '用户' : '家长');
                $sheet->setCellValue('T' . $key, $admin[$item['department_id']]['user_name'] ?? '--');
            }
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/gz' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }

    /**
     * 干预人群导出
     * @param array $id 列表id
     * @param int $unit_id 单位id
     * @return string
     */
    public function InterfereUserExport(array $id, int $unit_id): string
    {
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 设置工作表标题
        $sheet->setTitle('干预人群');
        // 设置单元格数据
        $sheet->setCellValue('A1', '名称');
        $sheet->setCellValue('B1', '性别');
        $sheet->setCellValue('C1', '年龄');
        $sheet->setCellValue('D1', '预检建议优先度');
        $sheet->setCellValue('E1', '干预负责人');
        $sheet->setCellValue('F1', '正在第几次跟进');
        $sheet->setCellValue('G1', '加入干预人群时间');
        $sheet->setCellValue('H1', '危机风险等级');
        $sheet->setCellValue('I1', '疑似问题类型');
        $sheet->setCellValue('J1', '存在的异常行为表现');
        $sheet->setCellValue('K1', '发现途径');
        $sheet->setCellValue('L1', '所在单位');
        $sheet->setCellValue('M1', '所属部门');
        $sheet->setCellValue('N1', '所在部门');
        $sheet->setCellValue('O1', '编号');
//        $sheet->setCellValue('P1', '学籍状态');
        $sheet->setCellValue('P1', '注册账号');
        $sheet->setCellValue('Q1', '所在部门管理员');
        $InterfereUserModel = new InterfereUserModel();
        $data = $InterfereUserModel->where('id', 'in', $id)->with([
            'user' => function ($query) {
                $query->with(['unitName']);
            },
            'InterfereBehavior' => function ($query) {
                $query->with(['CrisisBehavior']);
            },
            'OperatorUser' => function ($query) {
                $query->with(['roleName']);
            },
            'CrisisLevel',
            'CrisisType'
        ])->select()->toArray();
        if (count($data) > 0) {
            $department_id = array_column($data, 'department_id');
            $UserService = new UserService($this->app);
            $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
            $getDepartmentAdminAll = $UserService->getDepartmentAdminAll($department_id);
            foreach ($data as $key => $item) {
                $item['operator_role_name'] = $item['operator_role_name'] ?? "超级管理员";
                //优先级
                $priority_name = match ($item['priority']) {
                    1 => '高度优先',
                    2 => '重度优先',
                    3 => '低度优先',
                    default => '--',
                };
                //异常行为
                $InterfereBehavior = array_column($item['InterfereBehavior'], 'behavior_name');
                $behavior_name = implode('、', $InterfereBehavior);
                //途径
                $channel_name = match ($item['channel']) {
                    1 => '危机上报手动移入',
                    2 => '任务测评自动加入',
                    3 => '自我测评自动加入',
                    4 => '他人代测自动移入',
                    5 => '无线测评自动移入',
                    6 => '线上咨询手动移入',
                    7 => '线下预约手动移入',
                    8 => '关注人群手动导入',
                    9 => '干预人群手动导入',
                    default => '--',
                };
                //学籍状态
                $item['student_name'] = match ($item['student_status']) {
                    1 => '在读',
                    2 => '已毕业',
                    3 => '已退学',
                    4 => '休学',
                    default => '--',
                };
                // 设置单元格数据
                $key = $key + 2;
                $sheet->setCellValue('A' . $key, $item['user_name']);
                $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                $sheet->setCellValue('C' . $key, $item['user_age'] ?: '--');
                $sheet->setCellValue('D' . $key, $priority_name);
                $sheet->setCellValue('E' . $key, $item['operator_name'] . '(' . $item['operator_role_name'] . ')');
                $sheet->setCellValue('F' . $key, $item['up_num']);
                $sheet->setCellValue('G' . $key, date('Y-m-d H:i:s', $item['time']));
                $sheet->setCellValue('H' . $key, $item['level_name']);
                $sheet->setCellValue('I' . $key, $item['type_name']);
                $sheet->setCellValue('J' . $key, $behavior_name);
                $sheet->setCellValue('K' . $key, $channel_name);
                $sheet->setCellValue('L' . $key, $item['unit_name']);
                $sheet->setCellValue('M' . $key, $DepartmentAffiliationAll[$item['department_id']]['ascription_name'] ?? '--');
                $sheet->setCellValue('N' . $key, $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '--');
                $sheet->setCellValue('O' . $key, $item['user_number']);
//                $sheet->setCellValue('P' . $key, $item['student_name']);
                $sheet->setCellValue('P' . $key, $item['username'].' ');
                $sheet->setCellValue('Q' . $key, $getDepartmentAdminAll[$item['department_id']]['user_name'] ?? '--');
            }
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/gy' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }

    /**
     * 干预完成档案导出
     * @param array $id 列表id
     * @param int $unit_id 单位id
     * @return string
     */
    public function InterfereUserArchivesExport(array $id, int $unit_id): string
    {
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 设置工作表标题
        $sheet->setTitle('干预完成档案');
        // 设置单元格数据
        $sheet->setCellValue('A1', '名称');
        $sheet->setCellValue('B1', '性别');
        $sheet->setCellValue('C1', '年龄');
        $sheet->setCellValue('D1', '归档次数');
        $sheet->setCellValue('E1', '归档时间');
        $sheet->setCellValue('F1', '危机风险等级');
        $sheet->setCellValue('G1', '疑似问题类型');
        $sheet->setCellValue('H1', '存在的异常行为表现');
        $sheet->setCellValue('I1', '发现途径');
        $sheet->setCellValue('J1', '所在单位');
        $sheet->setCellValue('K1', '所在部门');
        $sheet->setCellValue('L1', '编号');
//        $sheet->setCellValue('M1', '学籍状态');
        $sheet->setCellValue('M1', '注册账号');
        $sheet->setCellValue('N1', '所在部门管理员');
        $InterfereUserModel = new InterfereUserModel();
        $data = $InterfereUserModel->where('id', 'in', $id)->with([
            'user' => function ($query) {
                $query->with(['unitName']);
            },
            'InterfereBehavior' => function ($query) {
                $query->with(['CrisisBehavior']);
            },
            'OperatorUser' => function ($query) {
                $query->with(['roleName']);
            },
            'CrisisLevel',
            'CrisisType'
        ])->select()->toArray();
        if (!empty($data)) {
            $department_id = array_column($data, 'department_id');
            $UserService = new UserService($this->app);
            $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
            $getDepartmentAdminAll = $UserService->getDepartmentAdminAll($department_id);
            foreach ($data as $key => $item) {
                //异常行为
                $InterfereBehavior = array_column($item['InterfereBehavior'], 'behavior_name');
                $behavior_name = implode('、', $InterfereBehavior);
                //途径
                $channel_name = match ($item['channel']) {
                    1 => '危机上报手动移入',
                    2 => '任务测评自动加入',
                    3 => '自我测评自动加入',
                    4 => '他人代测自动移入',
                    5 => '无线测评自动移入',
                    6 => '线上咨询手动移入',
                    7 => '线下预约手动移入',
                    8 => '关注人群手动导入',
                    9 => '干预人群手动导入',
                    default => '--',
                };
                //学籍状态
                $item['student_name'] = match ($item['student_status']) {
                    1 => '在读',
                    2 => '已毕业',
                    3 => '已退学',
                    4 => '休学',
                    default => '--',
                };
                // 设置单元格数据
                $key = $key + 2;
                $sheet->setCellValue('A' . $key, $item['user_name']);
                $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                $sheet->setCellValue('C' . $key, $item['user_age']);
                $sheet->setCellValue('D' . $key, $item['status_num']);
                $sheet->setCellValue('E' . $key, date('Y-m-d H:i:s', $item['status_time']));
                $sheet->setCellValue('F' . $key, $item['level_name']);
                $sheet->setCellValue('G' . $key, $item['type_name']);
                $sheet->setCellValue('H' . $key, $behavior_name);
                $sheet->setCellValue('I' . $key, $channel_name);
                $sheet->setCellValue('J' . $key, $item['unit_name']);
                $sheet->setCellValue('K' . $key, $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '--');
                $sheet->setCellValue('L' . $key, $item['user_number'] ?: '--');
//                $sheet->setCellValue('M' . $key, $item['student_name']);
                $sheet->setCellValue('M' . $key, $item['username'].' ');
                $sheet->setCellValue('N' . $key, $getDepartmentAdminAll[$item['department_id']]['user_name'] ?? '--');
            }
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/gyda' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }

    /**
     * 危机干预月报导出
     * @param array $param 检索条件
     * @param array $userData 操作人信息
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function MonthlyReport(array $param, array $userData): string
    {
        $unit_id = $userData['unit_id'];
        $i = 0;
        $start_time = strtotime(date($param['date'] . '-01'));
        $end_time = strtotime(date($param['date'] . '-t 23:59:59'));
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        if (in_array(1, $param['channel'])) {
            // 获取活动的工作表
            $sheet = $spreadsheet->setActiveSheetIndex($i);
            // 设置工作表标题
            $sheet->setTitle('关注人群');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '性别');
            $sheet->setCellValue('C1', '年龄');
            $sheet->setCellValue('D1', '所在部门');
            $sheet->setCellValue('E1', '编号');
            $sheet->setCellValue('F1', '关注等级');
            $sheet->setCellValue('G1', '关注负责人');
            $sheet->setCellValue('H1', '正在第几次跟进');
            $sheet->setCellValue('I1', '测评报告等级');
            $sheet->setCellValue('J1', '发现途径');
            $sheet->setCellValue('K1', '测评量表和结果');
            $sheet->setCellValue('L1', '允许查报告权限');
            $sheet->setCellValue('M1', '加入关注时间');
            $sheet->setCellValue('N1', '测评量表分类');
            $sheet->setCellValue('O1', '测评总分');
            $sheet->setCellValue('P1', '申请报告解读');
            $sheet->setCellValue('Q1', '所在单位');
            $sheet->setCellValue('R1', '学籍状态');
            $sheet->setCellValue('S1', '注册账号');
            $sheet->setCellValue('T1', '测评用户类型');
            $sheet->setCellValue('U1', '所在部门管理员');
            $FollowUserModel = new FollowUserModel();
            $data = $FollowUserModel->where('time', 'between', [$start_time, $end_time])
                ->with([
                    'operator',
                    'user' => function ($query) {
                        $query->with(['unitName']);
                    }
                ])->select()->toArray();
            if (!empty($data)) {
                $department_id = array_column($data, 'department_id');
                $UserService = new UserService($this->app);
                $admin = $UserService->getDepartmentAdminAll($department_id);
                $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
                foreach ($data as $key => $item) {
                    switch ($item['channel']) {
                        case 2:
                            $TaskUserResultModel = new TaskUserResultModel();
                            $result = $TaskUserResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = $result['answer_role'];
                            break;
                        case 3:
                            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                            $result = $SelfEvaluationResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = $result['answer_role'];
                            break;
                        case 4:
                            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
                            $result = $ProxyEvaluationResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = $result['answer_role'];
                            break;
                        case 6:
                            $ConsultOnlineResultModel = new ConsultOnlineResultModel();
                            $result = $ConsultOnlineResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = '';
                            break;
                        case 7:
                            $ConsultOfflineResultModel = new ConsultOfflineResultModel();
                            $result = $ConsultOfflineResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = '';
                            break;
                        default:
                            $item['rating_scale_name'] = '';
                            $item['warning_name'] = '';
                            $item['result_read_auth'] = '';
                            $item['total_score'] = '';
                            $item['is_explain'] = '';
                            $item['rating_scale_type_name'] = '';
                            $item['answer_role'] = '';
                    }
                    $item['level_name'] = match ($item['level']) {
                        1 => '轻度',
                        2 => '中度',
                        3 => '重度',
                        4 => '密切',
                        default => '--',
                    };
                    $item['channel_name'] = match ($item['channel']) {
                        1 => '危机上报手动移入',
                        2 => '任务测评自动加入',
                        3 => '自我测评自动加入',
                        4 => '他人代测自动移入',
                        5 => '无线测评自动移入',
                        6 => '线上咨询手动移入',
                        7 => '线下预约手动移入',
                        8 => '关注人群手动导入',
                        9 => '干预人群手动导入',
                        default => '--',
                    };
                    $item['explain_name'] = match ($item['is_explain']) {
                        1 => '未解读',
                        2 => '申请中',
                        3 => '已解读',
                        default => '--',
                    };
                    $item['student_name'] = match ($item['student_status']) {
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if (isset($item['result_read_auth']) && !empty($item['result_read_auth'])) {
                        $result_read_auth = explode(',', $item['result_read_auth']);
                        $auth_name = '';
                        foreach ($result_read_auth as $v) {
                            $auth_name .= match ($v) {
                                    '1' => '管理员',
                                    '2' => '咨询师',
                                    '3' => '用户',
                                    '4' => '家长',
                                    default => '',
                                } . '、';
                        }
                        $auth_name = rtrim($auth_name);
                    } else {
                        $auth_name = '--';
                    }
                    // 设置单元格数据
                    $key = $key + 2;
                    $sheet->setCellValue('A' . $key, $item['user_name']);
                    $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('C' . $key, $item['user_age']);
                    $sheet->setCellValue('D' . $key, $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '--');
                    $sheet->setCellValue('E' . $key, $item['user_number'] ?: '--');
                    $sheet->setCellValue('F' . $key, $item['level_name']);
                    $sheet->setCellValue('G' . $key, $item['operator_name']);
                    $sheet->setCellValue('H' . $key, $item['up_num']);
                    $sheet->setCellValue('I' . $key, $item['warning_name']);
                    $sheet->setCellValue('J' . $key, $item['channel_name']);
                    $sheet->setCellValue('K' . $key, $item['rating_scale_name']);
                    $sheet->setCellValue('L' . $key, $auth_name);
                    $sheet->setCellValue('M' . $key, date('Y-m-d H:i:s', $item['time']));
                    $sheet->setCellValue('N' . $key, $item['rating_scale_type_name']);
                    $sheet->setCellValue('O' . $key, $item['total_score']);
                    $sheet->setCellValue('P' . $key, $item['explain_name']);
                    $sheet->setCellValue('Q' . $key, $item['unit_name']);
                    $sheet->setCellValue('R' . $key, $item['student_name']);
                    $sheet->setCellValue('S' . $key, $item['username'].' ');
                    $sheet->setCellValue('T' . $key, $item['answer_role'] == 1 ? '用户' : '家长');
                    $sheet->setCellValue('U' . $key, $admin[$item['department_id']]['user_name'] ?? '--');
                }
            }
        }
        if (in_array(2, $param['channel'])) {
            /**
             * 干预人群
             */
            $i++;
            // 获取活动的工作表
            $spreadsheet->createSheet();
            $sheet = $spreadsheet->setActiveSheetIndex($i);
            // 设置工作表标题
            $sheet->setTitle('干预人群');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '性别');
            $sheet->setCellValue('C1', '年龄');
            $sheet->setCellValue('D1', '预检建议优先度');
            $sheet->setCellValue('E1', '干预负责人');
            $sheet->setCellValue('F1', '正在第几次跟进');
            $sheet->setCellValue('G1', '加入干预人群时间');
            $sheet->setCellValue('H1', '危机风险等级');
            $sheet->setCellValue('I1', '疑似问题类型');
            $sheet->setCellValue('J1', '存在的异常行为表现');
            $sheet->setCellValue('K1', '发现途径');
            $sheet->setCellValue('L1', '所在单位');
            $sheet->setCellValue('M1', '所属部门');
            $sheet->setCellValue('N1', '所在部门');
            $sheet->setCellValue('O1', '编号');
            $sheet->setCellValue('P1', '学籍状态');
            $sheet->setCellValue('Q1', '注册账号');
            $sheet->setCellValue('R1', '所在部门管理员');
            $InterfereUserModel = new InterfereUserModel();
            $where = [
                ['time', 'between', [$start_time, $end_time]],
                ['move_status', '=', 1],
                ['status', '=', 0]
            ];
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', 'in', $param['type_id']];
            }
            $data = $InterfereUserModel->where($where)->with([
                'user' => function ($query) {
                    $query->with(['unitName']);
                },
                'InterfereBehavior' => function ($query) {
                    $query->with(['CrisisBehavior']);
                },
                'OperatorUser' => function ($query) {
                    $query->with(['roleName']);
                },
                'CrisisLevel',
                'CrisisType'
            ])->select()->toArray();
            if (!empty($data)) {
                $department_id = array_column($data, 'department_id');
                $UserService = new UserService($this->app);
                $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
                $getDepartmentAdminAll = $UserService->getDepartmentAdminAll($department_id);
                foreach ($data as $key => $item) {
                    $item['operator_role_name'] = $item['operator_role_name'] ?? "超级管理员";
                    //优先级
                    $priority_name = match ($item['priority']) {
                        1 => '高度优先',
                        2 => '重度优先',
                        3 => '低度优先',
                        default => '--',
                    };
                    //异常行为
                    $InterfereBehavior = array_column($item['InterfereBehavior'], 'behavior_name');
                    $behavior_name = implode('、', $InterfereBehavior);
                    //途径
                    $channel_name = match ($item['channel']) {
                        1 => '危机上报手动移入',
                        2 => '任务测评自动加入',
                        3 => '自我测评自动加入',
                        4 => '他人代测自动移入',
                        5 => '无线测评自动移入',
                        6 => '线上咨询手动移入',
                        7 => '线下预约手动移入',
                        8 => '关注人群手动导入',
                        9 => '干预人群手动导入',
                        default => '--',
                    };
                    //学籍状态
                    $item['student_name'] = match ($item['student_status']) {
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    // 设置单元格数据
                    $key = $key + 2;
                    $sheet->setCellValue('A' . $key, $item['user_name']);
                    $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('C' . $key, $item['user_age']);
                    $sheet->setCellValue('D' . $key, $priority_name);
                    $sheet->setCellValue('E' . $key, $item['operator_name'] . '(' . $item['operator_role_name'] . ')');
                    $sheet->setCellValue('F' . $key, $item['up_num']);
                    $sheet->setCellValue('G' . $key, date('Y-m-d H:i:s', $item['time']));
                    $sheet->setCellValue('H' . $key, $item['level_name']);
                    $sheet->setCellValue('I' . $key, $item['type_name']);
                    $sheet->setCellValue('J' . $key, $behavior_name);
                    $sheet->setCellValue('K' . $key, $channel_name);
                    $sheet->setCellValue('L' . $key, $item['unit_name']);
                    $sheet->setCellValue('M' . $key, $DepartmentAffiliationAll[$item['department_id']]['ascription_name'] ?? '--');
                    $sheet->setCellValue('N' . $key, $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '--');
                    $sheet->setCellValue('O' . $key, $item['user_number'] ?: '--');
                    $sheet->setCellValue('P' . $key, $item['student_name']);
                    $sheet->setCellValue('Q' . $key, $item['username'].' ');
                    $sheet->setCellValue('R' . $key, $getDepartmentAdminAll[$item['department_id']]['user_name'] ?? '--');
                }
            }
        }
        if (in_array(3, $param['channel'])) {
            /**
             * 干预完成档案
             */
            $i++;
            $spreadsheet->createSheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->setActiveSheetIndex($i);
            // 设置工作表标题
            $sheet->setTitle('干预完成档案');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '性别');
            $sheet->setCellValue('C1', '年龄');
            $sheet->setCellValue('D1', '归档次数');
            $sheet->setCellValue('E1', '归档时间');
            $sheet->setCellValue('F1', '危机风险等级');
            $sheet->setCellValue('G1', '疑似问题类型');
            $sheet->setCellValue('H1', '存在的异常行为表现');
            $sheet->setCellValue('I1', '发现途径');
            $sheet->setCellValue('J1', '所在单位');
            $sheet->setCellValue('K1', '所属部门');
            $sheet->setCellValue('L1', '所在部门');
            $sheet->setCellValue('M1', '编号');
            $sheet->setCellValue('N1', '学籍状态');
            $sheet->setCellValue('O1', '注册账号');
            $sheet->setCellValue('P1', '所在部门管理员');
            $InterfereUserModel = new InterfereUserModel();
            $where = [
                ['time', 'between', [$start_time, $end_time]],
                ['move_status', '=', 1],
                ['status', '=', 1]
            ];
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', 'in', $param['type_id']];
            }
            $data = $InterfereUserModel->where($where)->with([
                'user' => function ($query) {
                    $query->with(['unitName']);
                },
                'InterfereBehavior' => function ($query) {
                    $query->with(['CrisisBehavior']);
                },
                'OperatorUser' => function ($query) {
                    $query->with(['roleName']);
                },
                'CrisisLevel',
                'CrisisType'
            ])->select()->toArray();
            if (!empty($data)) {
                $department_id = array_column($data, 'department_id');
                $UserService = new UserService($this->app);
                $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
                $getDepartmentAdminAll = $UserService->getDepartmentAdminAll($department_id);
                foreach ($data as $key => $item) {
                    //异常行为
                    $InterfereBehavior = array_column($item['InterfereBehavior'], 'behavior_name');
                    $behavior_name = implode('、', $InterfereBehavior);
                    //途径
                    $channel_name = match ($item['channel']) {
                        1 => '危机上报手动移入',
                        2 => '任务测评自动加入',
                        3 => '自我测评自动加入',
                        4 => '他人代测自动移入',
                        5 => '无线测评自动移入',
                        6 => '线上咨询手动移入',
                        7 => '线下预约手动移入',
                        8 => '关注人群手动导入',
                        9 => '干预人群手动导入',
                        default => '--',
                    };
                    //学籍状态
                    $item['student_name'] = match ($item['student_status']) {
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    // 设置单元格数据
                    $key = $key + 2;
                    $sheet->setCellValue('A' . $key, $item['user_name']);
                    $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('C' . $key, $item['user_age']);
                    $sheet->setCellValue('D' . $key, $item['status_num']);
                    $sheet->setCellValue('E' . $key, date('Y-m-d H:i:s', $item['status_time']));
                    $sheet->setCellValue('F' . $key, $item['level_name']);
                    $sheet->setCellValue('G' . $key, $item['type_name']);
                    $sheet->setCellValue('H' . $key, $behavior_name);
                    $sheet->setCellValue('I' . $key, $channel_name);
                    $sheet->setCellValue('J' . $key, $item['unit_name']);
                    $sheet->setCellValue('K' . $key, $DepartmentAffiliationAll[$item['department_id']]['ascription_name'] ?? '--');
                    $sheet->setCellValue('L' . $key, $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '--');
                    $sheet->setCellValue('M' . $key, $item['user_number'] ?: '--');
                    $sheet->setCellValue('N' . $key, $item['student_name']);
                    $sheet->setCellValue('O' . $key, $item['username'].' ');
                    $sheet->setCellValue('P' . $key, $getDepartmentAdminAll[$item['department_id']]['user_name'] ?? '--');
                }
            }
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/monthlyReport' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }

    /**
     * 用户危机干预档案归档情况导出
     * @param int $id
     * @param int $unit_id
     * @return string
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function ArchivingStatus(int $id, int $unit_id): string
    {
        $InterfereUserModel = new InterfereUserModel();
        $data = $InterfereUserModel->with([
            'OperatorUser' => function ($query) {
                $query->with(['roleName']);
            },
            'user' => function ($query) {
                $query->with([
                    'unitName',
                    'roleName',
                    'department' => function ($query) {
                        $query->with([
                            'departmentAdmins' => function ($query) {
                                $query->with(['userName']);
                            }
                        ]);
                    }
                ]);
            },
            'InterfereBehavior' => function ($query) {
                $query->with(['CrisisBehavior']);
            },
            'CrisisLevel',
            'CrisisType',
            'FollowUser'
        ])->find($id)->toArray();
        $channel = date('Y-m-d', $data['follow_time']) . '移入关注人群。' . date('Y-m-d', $data['time']) . '移入干预人群。' . date('Y-m-d', $data['status_time']) . '日干预完结后，';
        switch ($data['channel']) {
            case 2:
                $channel = '量表测评--任务测评。测评结果显示预警后，自动加入关注人群名单。'.date('Y-m-d', $data['time']) . '移入干预人群。' . date('Y-m-d', $data['status_time']) . '日干预完结后，';
                $TaskUserResultModel = new TaskUserResultModel();
                $result = $TaskUserResultModel->with([
                    'RatingScale' => function ($query) {
                        $query->with(['RatingScaleTypeName']);
                    },
                    'RatingScaleFactorWarningModel' => function ($query) {
                        $query->with(['factorName']);
                    },
                ])->find($data['channel_id']);
                if (!$result) break;
                $data['factor_name'] = $result['factor_name'];
                $data['warning_name'] = $result['warning_name'];
                $data['rating_scale_type_name'] = $result['rating_scale_type_name'];
                $data['total_score'] = $result['total_score'];
                $data['result_time'] = date('Y-m-d H:i:s', $result['time']);
                $data['is_explain'] = $result['is_explain'];
                break;
            case 3:
                $channel = '量表测评--自我测评。测评结果显示预警后，自动加入关注人群名单。'.date('Y-m-d', $data['time']) . '移入干预人群。' . date('Y-m-d', $data['status_time']) . '日干预完结后，';
                $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                $result = $SelfEvaluationResultModel->with([
                    'RatingScale' => function ($query) {
                        $query->with(['RatingScaleTypeName']);
                    },
                    'RatingScaleFactorWarningModel' => function ($query) {
                        $query->with(['factorName']);
                    },
                ])->find($data['channel_id']);
                if (!$result) break;
                $data['factor_name'] = $result['factor_name'];
                $data['warning_name'] = $result['warning_name'];
                $data['rating_scale_type_name'] = $result['rating_scale_type_name'];
                $data['total_score'] = $result['total_score'];
                $data['result_time'] = date('Y-m-d H:i:s', $result['time']);
                $data['is_explain'] = $result['is_explain'];
                break;
            case 4:
                $channel = '量表测评--他人代测。测评结果显示预警后，自动加入关注人群名单。'.date('Y-m-d', $data['time']) . '移入干预人群。' . date('Y-m-d', $data['status_time']) . '日干预完结后，';
                $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
                $result = $ProxyEvaluationResultModel->with([
                    'RatingScale' => function ($query) {
                        $query->with(['RatingScaleTypeName']);
                    },
                    'RatingScaleFactorWarningModel' => function ($query) {
                        $query->with(['factorName']);
                    },
                ])->find($data['channel_id']);
                if (!$result) break;
                $data['factor_name'] = $result['factor_name'];
                $data['warning_name'] = $result['warning_name'];
                $data['rating_scale_type_name'] = $result['rating_scale_type_name'];
                $data['total_score'] = $result['total_score'];
                $data['result_time'] = date('Y-m-d H:i:s', $result['time']);
                $data['is_explain'] = $result['is_explain'];
                break;
            case 6:
                $channel = '量表测评--线上咨询。测评结果显示预警后，手动移入关注人群名单。'.date('Y-m-d', $data['time']) . '移入干预人群。' . date('Y-m-d', $data['status_time']) . '日干预完结后，';
                $ConsultOnlineResultModel = new ConsultOnlineResultModel();
                $result = $ConsultOnlineResultModel->with([
                    'RatingScale' => function ($query) {
                        $query->with(['RatingScaleTypeName']);
                    },
                    'RatingScaleFactorWarningModel' => function ($query) {
                        $query->with(['factorName']);
                    },
                ])->find($data['channel_id']);
                if (!$result) break;
                $data['factor_name'] = $result['factor_name'];
                $data['warning_name'] = $result['warning_name'];
                $data['rating_scale_type_name'] = $result['rating_scale_type_name'];
                $data['total_score'] = $result['total_score'];
                $data['result_time'] = date('Y-m-d H:i:s', $result['time']);
                $data['is_explain'] = $result['is_explain'];
                break;
            case 7:
                $channel = '量表测评--线下预约。测评结果显示预警后，手动移入关注人群名单。'.date('Y-m-d', $data['time']) . '移入干预人群。' . date('Y-m-d', $data['status_time']) . '日干预完结后，';
                $ConsultOfflineResultModel = new ConsultOfflineResultModel();
                $result = $ConsultOfflineResultModel->with([
                    'RatingScale' => function ($query) {
                        $query->with(['RatingScaleTypeName']);
                    },
                    'RatingScaleFactorWarningModel' => function ($query) {
                        $query->with(['factorName']);
                    },
                ])->find($data['channel_id']);
                if (!$result) break;
                $data['factor_name'] = $result['factor_name'];
                $data['warning_name'] = $result['warning_name'];
                $data['rating_scale_type_name'] = $result['rating_scale_type_name'];
                $data['rating_scale_name'] = $result['rating_scale_name'];
                $data['total_score'] = $result['total_score'];
                $data['result_time'] = date('Y-m-d H:i:s', $result['time']);
                $data['is_explain'] = $result['is_explain'];
                break;
            case 8:
                $channel = date('Y-m-d', $data['time']) . '移入干预人群。' . date('Y-m-d', $data['status_time']) . '日干预完结后，';
                break;
            case 9:
                $channel = date('Y-m-d', $data['time']) . '手动导入干预人群。' . date('Y-m-d', $data['status_time']) . '日干预完结后，';
                break;
        }
        //部门管理
        if (!empty($data['departmentAdmins'])) {
            $department_admin = '';
            foreach ($data['departmentAdmins'] as $value) {
                $department_admin .= $value['user_name'] . '、';
            }
            $department_admin = rtrim($department_admin, "、");
        } else {
            $department_admin = '--';
        }
        //学籍状态
        $student_status = match ($data['student_status']) {
            1 => '在读',
            2 => '已毕业',
            3 => '已退学',
            4 => '休学',
            default => '--',
        };
        //解读情况
        if (isset($data['is_explain'])) {
            $explain_name = match ($data['is_explain']) {
                1 => '未解读',
                2 => '申请中',
                3 => '已解读',
                default => '--',
            };
        } else {
            $explain_name = '--';
        }
        //异常行为
        $InterfereBehavior = array_column($data['InterfereBehavior'], 'behavior_name');
        if (!empty($InterfereBehavior)) {
            $behavior_name = implode('、', $InterfereBehavior);
        } else {
            $behavior_name = '--';
        }
        //干预措施
        if (!empty($data['up_content'])) {
            $up_content = json_decode($data['up_content'], true);
            $measure_id = [];
            foreach ($up_content as $value) {
                foreach ($value['measure'] as $v) {
                    $measure_id[] = $v;
                }
            }
            if (!empty($measure_id)) {
                $measure_id = array_unique($measure_id);
                $CrisisMeasuresModel = new CrisisMeasuresModel();
                $measure = $CrisisMeasuresModel->where('id', 'in', $measure_id)->column('name');
                $measure = implode('、', $measure);
            } else {
                $measure = '--';
            }
        } else {
            $measure = '--';
        }

        $UserService = new UserService($this->app);
        // 加载Word模板文档
        if (isset($data['rating_scale_name'])) {
            $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/archiving_status.docx');
        } else {
            $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/archiving_status2.docx');
        }
        // 定位并修改内容部分
        $templateProcessor->setValue('status_time', date('Y-m-d H:i:s', $data['status_time'])); // 替换模板中的变量
        $templateProcessor->setValue('user_name', $data['user_name']); // 替换模板中的变量
        $templateProcessor->setValue('username', $data['username']); // 替换模板中的变量
        $templateProcessor->setValue('role_name', $data['role_name']); // 替换模板中的变量
        $templateProcessor->setValue('user_age', $data['user_age']); // 替换模板中的变量
        $templateProcessor->setValue('phone', $data['phone']); // 替换模板中的变量
        $templateProcessor->setValue('user_sex', $data['user_sex'] == 1 ? '男' : '女'); // 替换模板中的变量
        $templateProcessor->setValue('region', $data['province_name'] . $data['city_name'] . $data['area_name']); // 替换模板中的变量
        $templateProcessor->setValue('unit_name', $data['unit_name']); // 替换模板中的变量
        $templateProcessor->setValue('department_name', $UserService->getNotDelDepartmentName($unit_id, $data['department_id'])); // 替换模板中的变量
        $templateProcessor->setValue('user_number', $data['user_number'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('department_admin', $department_admin); // 替换模板中的变量
        $templateProcessor->setValue('student_status', $student_status); // 替换模板中的变量
        $templateProcessor->setValue('channel', $channel); // 替换模板中的变量
        $templateProcessor->setValue('rating_scale_name', $data['rating_scale_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('rating_scale_type_name', $data['rating_scale_type_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('rating_scale_type_name', $data['rating_scale_type_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('score', $data['total_score'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('warning_name', $data['warning_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('warning_factor_name', $data['factor_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('explain_name', $explain_name); // 替换模板中的变量
        $templateProcessor->setValue('result_time', $data['result_time'] ?? '--'); // 替换模板中的变量

        $FollowUserModel = new FollowUserModel();
        $FollowUserInfo = $FollowUserModel->with([
            'operator' => function ($query) {
                $query->with(['roleName']);
            }
        ])->find($data['follow_id']);
        if (isset($FollowUserInfo)) {
            $templateProcessor->setValue('follow_reason', $FollowUserInfo['reason'] ?? '--'); // 替换模板中的变量
            $templateProcessor->setValue('follow_time', date('Y-m-d H:i:s', $FollowUserInfo['time']) . '--' .date('Y-m-d H:i:s', $data['time'])); // 替换模板中的变量
            $templateProcessor->setValue('follow_operator_name', $FollowUserInfo['operator_name'] ?? '--'); // 替换模板中的变量
            $templateProcessor->setValue('follow_operator_role_name', $FollowUserInfo['operator_role_name'] ?? '--'); // 替换模板中的变量
            $templateProcessor->setValue('follow_up_num', $FollowUserInfo['up_num'] ?? ' 0 '); // 替换模板中的变量
        } else {
            $templateProcessor->setValue('follow_reason', '--'); // 替换模板中的变量
            $templateProcessor->setValue('follow_time', '--'); // 替换模板中的变量
            $templateProcessor->setValue('follow_operator_name', '--'); // 替换模板中的变量
            $templateProcessor->setValue('follow_up_num', '--'); // 替换模板中的变量
        }
        $templateProcessor->setValue('describe', $data['describe'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('time', date('Y-m-d H:i:s', $data['time']) . '--' . date('Y-m-d H:i:s', $data['status_time'])); // 替换模板中的变量
        $templateProcessor->setValue('operator_name', $data['operator_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('operator_role_name', $data['operator_role_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('up_num', $data['up_num'] ?? ' 0 '); // 替换模板中的变量
        $templateProcessor->setValue('type_name', $data['type_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('behavior_name', $behavior_name); // 替换模板中的变量
        $templateProcessor->setValue('level_name', $data['level_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('risk', $data['level_explain'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('measure', $measure); // 替换模板中的变量

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/export/archiving_status' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }

    /**
     * 关注期情况记录表导出
     * @param int $id
     * @return bool|string
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function FollowArchive(int $id): bool|string
    {
        $InterfereUserModel = new InterfereUserModel();
        $InterfereUserInfo = $InterfereUserModel->find($id);
        if (!$InterfereUserInfo || !$InterfereUserInfo['follow_id']) return false;
        $FollowUserModel = new FollowUserModel();
        $FollowUserInfo = $FollowUserModel->with([
            'operator' => function ($query) {
                $query->with(['roleName']);
            }
        ])->find($InterfereUserInfo['follow_id']);
        if (!$FollowUserInfo) return false;
        //渠道
        $channel = match ($FollowUserInfo['channel']) {
            1 => '危机上报手动移入',
            2 => '任务测评自动加入',
            3 => '自我测评自动加入',
            4 => '他人代测自动移入',
            5 => '无线测评自动移入',
            6 => '线上咨询手动移入',
            7 => '线下预约手动移入',
            8 => '关注人群手动导入',
            9 => '干预人群手动导入',
            default => '--',
        };
        //关注等级
        $level_name = match ($FollowUserInfo['level']) {
            1 => '轻度关注',
            2 => '中度关注',
            3 => '重度关注',
            4 => '密切关注',
            default => '--',
        };
        //跟进记录
        if (!empty($FollowUserInfo['up_content'])) {
            $up_content_list = json_decode($FollowUserInfo['up_content'], true);
            if (!empty($up_content_list)) {
                $up_content = '<w:br />';
                $i = 1;
                foreach ($up_content_list as $v) {
                    $up_content .= '第' . $i . '次跟进：' . date('Y-m-d', $v['time']) . " <w:br />";
                    $up_content .= $v['title'] . " <w:br />";
                    $up_content .= $v['content'] . " <w:br /> <w:br />";
                    $i++;
                }
            } else {
                $up_content = '--';
            }
        } else {
            $up_content = '--';
        }
        $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/follow_archive.docx');
        // 定位并修改内容部分
        $templateProcessor->setValue('archive_time', date('Y-m-d H:i:s', $InterfereUserInfo['time'])); // 替换模板中的变量
        $templateProcessor->setValue('time', date('Y-m-d H:i:s', $FollowUserInfo['time'])); // 替换模板中的变量
        $templateProcessor->setValue('channel', $channel); // 替换模板中的变量
        $templateProcessor->setValue('operator_name', $FollowUserInfo['operator_name']); // 替换模板中的变量
        $templateProcessor->setValue('operator_role_name', $FollowUserInfo['operator_role_name']); // 替换模板中的变量
        $templateProcessor->setValue('reason', $FollowUserInfo['reason']); // 替换模板中的变量
        $templateProcessor->setValue('level_name', $level_name); // 替换模板中的变量
        $templateProcessor->setValue('up_content', $up_content); // 替换模板中的变量

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/export/follow_archive' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }

    /**
     * 干预期情况记录表导出
     * @param int $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     */
    public function InterfereArchive(int $id): string
    {
        $InterfereUserModel = new InterfereUserModel();
        $InterfereUserInfo = $InterfereUserModel->with(['OperatorUser'])->find($id);
        if (!$InterfereUserInfo) return false;
        //渠道
        $channel = match ($InterfereUserInfo['channel']) {
            1 => '危机上报手动移入',
            2 => '任务测评自动加入',
            3 => '自我测评自动加入',
            4 => '他人代测自动移入',
            5 => '无线测评自动移入',
            6 => '线上咨询手动移入',
            7 => '线下预约手动移入',
            8 => '关注人群手动导入',
            9 => '干预人群手动导入',
            default => '--',
        };
        //跟进记录
        $CrisisMeasuresModel = new CrisisMeasuresModel();
        if (!empty($InterfereUserInfo['up_content'])) {
            $up_content_list = json_decode($InterfereUserInfo['up_content'], true);
            if (!empty($up_content_list)) {
                $up_content = " <w:br />";
                $i = 1;
                foreach ($up_content_list as $item) {
                    $up_content .= '第' . $i . '次跟进：' . date('Y-m-d', $item['time']) . " <w:br />";
                    //干预措施
                    $measure_id = [];
                    foreach ($item['measure'] as $v) {
                        $measure_id[] = $v;
                    }
                    if (!empty($measure_id)) {
                        $measure_id = array_unique($measure_id);
                        $measure = $CrisisMeasuresModel->where('id', 'in', $measure_id)->column('name');
                        $measure = implode('、', $measure);
                    } else {
                        $measure = '--';
                    }
                    $up_content .= '干预措施：' . $measure . " <w:br />";
                    //本次措施说明
                    $up_content .= '本次措施说明：' . $item['description'] . " <w:br />";
                    //本次干预结果
                    $up_content .= '本次干预结果：' . $item['result'] . " <w:br />";
                    //后续帮扶计划
                    $up_content .= '后续帮扶计划：' . $item['plan'] . " <w:br /> <w:br />";
                    $i++;
                }
            } else {
                $up_content = '--';
            }
        } else {
            $up_content = '--';
        }

        $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/interfere_archive.docx');
        // 定位并修改内容部分
        $templateProcessor->setValue('move_time', date('Y-m-d H:i:s', $InterfereUserInfo['move_time'])); // 替换模板中的变量
        $templateProcessor->setValue('channel', $channel); // 替换模板中的变量
        $templateProcessor->setValue('time', $InterfereUserInfo['time']); // 替换模板中的变量
        $templateProcessor->setValue('operator_name', $InterfereUserInfo['operator_name']); // 替换模板中的变量
        $templateProcessor->setValue('describe', $InterfereUserInfo['describe']); // 替换模板中的变量
        $templateProcessor->setValue('up_content', $up_content); // 替换模板中的变量

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/export/interfere_archive' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }


    /**
     * 干预完成记录-线上咨询记录导出
     * @param int $id 干预完成记录id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     */
    public function ArchivingConsultOnline(int $id): string
    {
        $InterfereUserModel = new InterfereUserModel();
        $InterfereUserInfo = $InterfereUserModel->find($id);
        if (!$InterfereUserInfo) return false;
        if ($InterfereUserInfo['channel'] != 6) return false;
        $ConsultOnlineResultModel = new ConsultOnlineResultModel();
        $ConsultOnlineModel = new ConsultOnlineModel();
        $ConsultOnlineMessageModel = new ConsultOnlineMessageModel();
        $source_id = $ConsultOnlineResultModel->where('id','=',$InterfereUserInfo['channel_id'])->value('source_id');
        $online_id = $ConsultOnlineMessageModel->where('id','=',$source_id)->value('online_id');
        $ConsultOnlineInfo = $ConsultOnlineModel->with(['questionName'])->find($online_id);
        $Message = $ConsultOnlineMessageModel
            ->where('online_id', '=', $online_id)->with([
                'user',
                'RatingScale'
            ])->select()->toArray();
        //咨询内容
        if (!empty($Message)) {
            $content = '';
            foreach ($Message as $item) {
                switch ($item['type']) {
                    case 1:
                        $content .= $item['user_name'] . '：' . $item['content'] . " <w:br />";
                        break;
                    case 2:
                        $content .= $item['user_name'] . '：自我测评任务' . " <w:br />";
                        break;
                    case 3:
                        $content .= $item['user_name'] . '：' . $item['rating_scale_name'] . " <w:br />";
                        break;
                }
            }
        } else {
            $content = ' ';
        }

        $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/online_consult.docx');
        // 定位并修改内容部分
        $templateProcessor->setValue('question_type', $ConsultOnlineInfo['question_name']); // 替换模板中的变量
        $templateProcessor->setValue('time', date('Y-m-d H:i:s',$ConsultOnlineInfo['time'])); // 替换模板中的变量
        $templateProcessor->setValue('is_end', $ConsultOnlineInfo['is_end']?'是':'否'); // 替换模板中的变量
        $templateProcessor->setValue('is_follow', $ConsultOnlineInfo['is_follow']?'是':'否'); // 替换模板中的变量
        $templateProcessor->setValue('describe', $ConsultOnlineInfo['describe']); // 替换模板中的变量
        $templateProcessor->setValue('content', $content); // 替换模板中的变量

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/export/online_consult' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }

    /**
     * 干预完成记录-线下预约记录导出
     * @param int $id 干预完成记录id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     */
    public function ArchivingConsultOffline(int $id): string
    {
        $InterfereUserModel = new InterfereUserModel();
        $InterfereUserInfo = $InterfereUserModel->find($id);
        if (!$InterfereUserInfo) return false;
        if ($InterfereUserInfo['channel'] != 7) return false;
        $ConsultOfflineResultModel = new ConsultOfflineResultModel();
        $ConsultOfflineModel = new ConsultOfflineModel();
        $ConsultOfflineTaskModel = new ConsultOfflineTaskModel();
        $source_id = $ConsultOfflineResultModel->where('id','=',$InterfereUserInfo['channel_id'])->value('source_id');
        $offline_id = $ConsultOfflineTaskModel->where('id','=',$source_id)->value('offline_id');
        $info = $ConsultOfflineModel->with([
            'questionName',
            'ConsultTime'
        ])->find($offline_id);
        $OfflineTask = $ConsultOfflineTaskModel
            ->where('offline_id', '=', $offline_id)->with([
                'RatingScale'
            ])->order('id','desc')->select()->toArray();
        //咨询内容
        if (!empty($OfflineTask)) {
            $task = '';
            $self = '';
            foreach ($OfflineTask as $item) {
                switch ($item['type']) {
                    case 1:
                        $self .= "自评任务 <w:br />";
                        break;
                    case 2:
                        $task .= $item['rating_scale_name'] . " <w:br />";
                        break;
                }
            }
        } else {
            $task = ' ';
            $self = ' ';
        }
        $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/offline_consult.docx');
        // 定位并修改内容部分
        $templateProcessor->setValue('question_type', $info['question_name']); // 替换模板中的变量
        $templateProcessor->setValue('time', date('Y-m-d H:i:s',$info['time'])); // 替换模板中的变量
        $templateProcessor->setValue('is_end', $info['is_end']?'是':'否'); // 替换模板中的变量
        $templateProcessor->setValue('type', $info['type'] == 1?'本人预约':'他人预约'); // 替换模板中的变量
        $templateProcessor->setValue('time_span', date('Y-m-d H:i',$info['reservation_start_time']).'-'.date('H:i',$info['reservation_end_time'])); // 替换模板中的变量
        $templateProcessor->setValue('is_follow', $info['is_follow']?'是':'否'); // 替换模板中的变量
        $templateProcessor->setValue('address', $info['address']); // 替换模板中的变量
        $templateProcessor->setValue('question', $info['question']); // 替换模板中的变量
        $templateProcessor->setValue('consult_reply', $info['consult_reply']); // 替换模板中的变量
        $templateProcessor->setValue('situation', $info['situation']); // 替换模板中的变量
        $templateProcessor->setValue('is_solve', $info['is_solve']); // 替换模板中的变量
        $templateProcessor->setValue('main_issues', $info['main_issues']); // 替换模板中的变量
        $templateProcessor->setValue('solution', $info['solution']); // 替换模板中的变量
        $templateProcessor->setValue('treatment_plan', $info['treatment_plan']); // 替换模板中的变量
        $templateProcessor->setValue('diagnostic_situation', $info['diagnostic_situation']); // 替换模板中的变量
        $templateProcessor->setValue('communication_records', $info['communication_records']); // 替换模板中的变量

        $templateProcessor->setValue('task', $task); // 替换模板中的变量
        $templateProcessor->setValue('self', $self); // 替换模板中的变量

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/export/offline_consult' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }



    /**
     * 危机干预月报导出-上报使用
     * @param array $param 检索条件
     * @param array $userData 操作人信息
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function MonthlyReport2(array $param, array $userData): string
    {
        $unit_id = $userData['unit_id'];
        $i = 0;
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->setActiveSheetIndex($i);
        // 设置工作表标题
        $sheet->setTitle('上报信息');
        // 设置单元格数据
        $sheet->setCellValue('A1', '上报数据类型');
        $sheet->setCellValue('B1', '包含异常问题');
        $sheet->setCellValue('C1', '危机人员心理动向');
        $sheet->setCellValue('D1', '心理健康建议');
        $sheet->setCellValue('E1', '特殊经历及感悟');
        $sheet->setCellValue('F1', '其他问题及建议');
        $sheet->setCellValue('G1', '自我工作评价');

        $param['channel'] = $param['channel']??[];
        $param['type_id'] = $param['type_id']??[];
        $channel_name = '';
        foreach ($param['channel'] as $k=>$v){
            if ($k == 0){
                $channel_name .= match ($v){
                    1 => '关注人群名单',
                    2 => '干预人群名单',
                    3 => '干预完成名单',
                    default => ''
                };
            }else{
                $channel_name .= '、'.match ($v){
                    1 => '关注人群名单',
                    2 => '干预人群名单',
                    3 => '干预完成名单',
                    default => ''
                };
            }
        }
        $CrisisTypeModel = new CrisisTypeModel();
        $type_name = $CrisisTypeModel->where('id','in',$param['type_id'])->column('name');
        $sheet->setCellValue('A2', $channel_name);
        $sheet->setCellValue('B2', implode('、',$type_name));
        $sheet->setCellValue('C2', $param['trend']);
        $sheet->setCellValue('D2', $param['health_advice']);
        $sheet->setCellValue('E2', $param['experience']);
        $sheet->setCellValue('F2', $param['suggestion']);
        $sheet->setCellValue('G2', $param['self_evaluation']);

        $start_time = $param['start_time'];
        $end_time = $param['end_time'];

        if (in_array(1, $param['channel'])) {
            // 获取活动的工作表
            $i++;
            // 获取活动的工作表
            $spreadsheet->createSheet();
            $sheet = $spreadsheet->setActiveSheetIndex($i);
            // 设置工作表标题
            $sheet->setTitle('关注人群');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '性别');
            $sheet->setCellValue('C1', '年龄');
            $sheet->setCellValue('D1', '所在部门');
            $sheet->setCellValue('E1', '编号');
            $sheet->setCellValue('F1', '关注等级');
            $sheet->setCellValue('G1', '关注负责人');
            $sheet->setCellValue('H1', '正在第几次跟进');
            $sheet->setCellValue('I1', '测评报告等级');
            $sheet->setCellValue('J1', '发现途径');
            $sheet->setCellValue('K1', '测评量表和结果');
            $sheet->setCellValue('L1', '允许查报告权限');
            $sheet->setCellValue('M1', '加入关注时间');
            $sheet->setCellValue('N1', '测评量表分类');
            $sheet->setCellValue('O1', '测评总分');
            $sheet->setCellValue('P1', '申请报告解读');
            $sheet->setCellValue('Q1', '所在单位');
            $sheet->setCellValue('R1', '学籍状态');
            $sheet->setCellValue('S1', '注册账号');
            $sheet->setCellValue('T1', '测评用户类型');
            $sheet->setCellValue('U1', '所在部门管理员');
            $FollowUserModel = new FollowUserModel();
            $data = $FollowUserModel->where('time', 'between', [$start_time, $end_time])
                ->with([
                    'operator',
                    'user' => function ($query) {
                        $query->with(['unitName']);
                    }
                ])->select()->toArray();
            if (!empty($data)) {
                $department_id = array_column($data, 'department_id');
                $UserService = new UserService($this->app);
                $admin = $UserService->getDepartmentAdminAll($department_id);
                $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
                foreach ($data as $key => $item) {
                    switch ($item['channel']) {
                        case 2:
                            $TaskUserResultModel = new TaskUserResultModel();
                            $result = $TaskUserResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = $result['answer_role'];
                            break;
                        case 3:
                            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                            $result = $SelfEvaluationResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = $result['answer_role'];
                            break;
                        case 4:
                            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
                            $result = $ProxyEvaluationResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = $result['answer_role'];
                            break;
                        case 6:
                            $ConsultOnlineResultModel = new ConsultOnlineResultModel();
                            $result = $ConsultOnlineResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = '';
                            break;
                        case 7:
                            $ConsultOfflineResultModel = new ConsultOfflineResultModel();
                            $result = $ConsultOfflineResultModel->with([
                                'RatingScaleFactorWarningModel',
                                'RatingScale' => function ($query) {
                                    $query->with(['ratingScaleTypeName']);
                                }
                            ])->find($item['channel_id']);
                            $item['rating_scale_name'] = $result['rating_scale_name'];
                            $item['warning_name'] = $result['warning_name'];
                            $item['result_read_auth'] = $result['result_read_auth'];
                            $item['total_score'] = $result['total_score'];
                            $item['is_explain'] = $result['is_explain'];
                            $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                            $item['answer_role'] = '';
                            break;
                        default:
                            $item['rating_scale_name'] = '';
                            $item['warning_name'] = '';
                            $item['result_read_auth'] = '';
                            $item['total_score'] = '';
                            $item['is_explain'] = '';
                            $item['rating_scale_type_name'] = '';
                            $item['answer_role'] = '';
                    }
                    $item['level_name'] = match ($item['level']) {
                        1 => '轻度',
                        2 => '中度',
                        3 => '重度',
                        4 => '密切',
                        default => '--',
                    };
                    $item['channel_name'] = match ($item['channel']) {
                        1 => '危机上报手动移入',
                        2 => '任务测评自动加入',
                        3 => '自我测评自动加入',
                        4 => '他人代测自动移入',
                        5 => '无线测评自动移入',
                        6 => '线上咨询手动移入',
                        7 => '线下预约手动移入',
                        8 => '关注人群手动导入',
                        9 => '干预人群手动导入',
                        default => '--',
                    };
                    $item['explain_name'] = match ($item['is_explain']) {
                        1 => '未解读',
                        2 => '申请中',
                        3 => '已解读',
                        default => '--',
                    };
                    $item['student_name'] = match ($item['student_status']) {
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if (isset($item['result_read_auth']) && !empty($item['result_read_auth'])) {
                        $result_read_auth = explode(',', $item['result_read_auth']);
                        $auth_name = '';
                        foreach ($result_read_auth as $v) {
                            $auth_name .= match ($v) {
                                    '1' => '管理员',
                                    '2' => '咨询师',
                                    '3' => '用户',
                                    '4' => '家长',
                                    default => '',
                                } . '、';
                        }
                        $auth_name = rtrim($auth_name);
                    } else {
                        $auth_name = '--';
                    }
                    // 设置单元格数据
                    $key = $key + 2;
                    $sheet->setCellValue('A' . $key, $item['user_name']);
                    $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('C' . $key, $item['user_age']);
                    $sheet->setCellValue('D' . $key, $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '--');
                    $sheet->setCellValue('E' . $key, $item['user_number'] ?: '--');
                    $sheet->setCellValue('F' . $key, $item['level_name']);
                    $sheet->setCellValue('G' . $key, $item['operator_name']);
                    $sheet->setCellValue('H' . $key, $item['up_num']);
                    $sheet->setCellValue('I' . $key, $item['warning_name']);
                    $sheet->setCellValue('J' . $key, $item['channel_name']);
                    $sheet->setCellValue('K' . $key, $item['rating_scale_name']);
                    $sheet->setCellValue('L' . $key, $auth_name);
                    $sheet->setCellValue('M' . $key, date('Y-m-d H:i:s', $item['time']));
                    $sheet->setCellValue('N' . $key, $item['rating_scale_type_name']);
                    $sheet->setCellValue('O' . $key, $item['total_score']);
                    $sheet->setCellValue('P' . $key, $item['explain_name']);
                    $sheet->setCellValue('Q' . $key, $item['unit_name']);
                    $sheet->setCellValue('R' . $key, $item['student_name']);
                    $sheet->setCellValue('S' . $key, $item['username'].' ');
                    $sheet->setCellValue('T' . $key, $item['answer_role'] == 1 ? '用户' : '家长');
                    $sheet->setCellValue('U' . $key, $admin[$item['department_id']]['user_name'] ?? '--');
                }
            }
        }
        if (in_array(2, $param['channel'])) {
            /**
             * 干预人群
             */
            $i++;
            // 获取活动的工作表
            $spreadsheet->createSheet();
            $sheet = $spreadsheet->setActiveSheetIndex($i);
            // 设置工作表标题
            $sheet->setTitle('干预人群');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '性别');
            $sheet->setCellValue('C1', '年龄');
            $sheet->setCellValue('D1', '预检建议优先度');
            $sheet->setCellValue('E1', '干预负责人');
            $sheet->setCellValue('F1', '正在第几次跟进');
            $sheet->setCellValue('G1', '加入干预人群时间');
            $sheet->setCellValue('H1', '危机风险等级');
            $sheet->setCellValue('I1', '疑似问题类型');
            $sheet->setCellValue('J1', '存在的异常行为表现');
            $sheet->setCellValue('K1', '发现途径');
            $sheet->setCellValue('L1', '所在单位');
            $sheet->setCellValue('M1', '所属部门');
            $sheet->setCellValue('N1', '所在部门');
            $sheet->setCellValue('O1', '编号');
            $sheet->setCellValue('P1', '学籍状态');
            $sheet->setCellValue('Q1', '注册账号');
            $sheet->setCellValue('R1', '所在部门管理员');
            $InterfereUserModel = new InterfereUserModel();
            $where = [
                ['time', 'between', [$start_time, $end_time]],
                ['move_status', '=', 1],
                ['status', '=', 0]
            ];
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', 'in', $param['type_id']];
            }
            $data = $InterfereUserModel->where($where)->with([
                'user' => function ($query) {
                    $query->with(['unitName']);
                },
                'InterfereBehavior' => function ($query) {
                    $query->with(['CrisisBehavior']);
                },
                'OperatorUser' => function ($query) {
                    $query->with(['roleName']);
                },
                'CrisisLevel',
                'CrisisType'
            ])->select()->toArray();
            if (!empty($data)) {
                $department_id = array_column($data, 'department_id');
                $UserService = new UserService($this->app);
                $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
                $getDepartmentAdminAll = $UserService->getDepartmentAdminAll($department_id);
                foreach ($data as $key => $item) {
                    $item['operator_role_name'] = $item['operator_role_name'] ?? "超级管理员";
                    //优先级
                    $priority_name = match ($item['priority']) {
                        1 => '高度优先',
                        2 => '重度优先',
                        3 => '低度优先',
                        default => '--',
                    };
                    //异常行为
                    $InterfereBehavior = array_column($item['InterfereBehavior'], 'behavior_name');
                    $behavior_name = implode('、', $InterfereBehavior);
                    //途径
                    $channel_name = match ($item['channel']) {
                        1 => '危机上报手动移入',
                        2 => '任务测评自动加入',
                        3 => '自我测评自动加入',
                        4 => '他人代测自动移入',
                        5 => '无线测评自动移入',
                        6 => '线上咨询手动移入',
                        7 => '线下预约手动移入',
                        8 => '关注人群手动导入',
                        9 => '干预人群手动导入',
                        default => '--',
                    };
                    //学籍状态
                    $item['student_name'] = match ($item['student_status']) {
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    // 设置单元格数据
                    $key = $key + 2;
                    $sheet->setCellValue('A' . $key, $item['user_name']);
                    $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('C' . $key, $item['user_age']);
                    $sheet->setCellValue('D' . $key, $priority_name);
                    $sheet->setCellValue('E' . $key, $item['operator_name'] . '(' . $item['operator_role_name'] . ')');
                    $sheet->setCellValue('F' . $key, $item['up_num']);
                    $sheet->setCellValue('G' . $key, date('Y-m-d H:i:s', $item['time']));
                    $sheet->setCellValue('H' . $key, $item['level_name']);
                    $sheet->setCellValue('I' . $key, $item['type_name']);
                    $sheet->setCellValue('J' . $key, $behavior_name);
                    $sheet->setCellValue('K' . $key, $channel_name);
                    $sheet->setCellValue('L' . $key, $item['unit_name']);
                    $sheet->setCellValue('M' . $key, $DepartmentAffiliationAll[$item['department_id']]['ascription_name'] ?? '--');
                    $sheet->setCellValue('N' . $key, $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '--');
                    $sheet->setCellValue('O' . $key, $item['user_number'] ?: '--');
                    $sheet->setCellValue('P' . $key, $item['student_name']);
                    $sheet->setCellValue('Q' . $key, $item['username'].' ');
                    $sheet->setCellValue('R' . $key, $getDepartmentAdminAll[$item['department_id']]['user_name'] ?? '--');
                }
            }
        }
        if (in_array(3, $param['channel'])) {
            /**
             * 干预完成档案
             */
            $i++;
            $spreadsheet->createSheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->setActiveSheetIndex($i);
            // 设置工作表标题
            $sheet->setTitle('干预完成档案');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '性别');
            $sheet->setCellValue('C1', '年龄');
            $sheet->setCellValue('D1', '归档次数');
            $sheet->setCellValue('E1', '归档时间');
            $sheet->setCellValue('F1', '危机风险等级');
            $sheet->setCellValue('G1', '疑似问题类型');
            $sheet->setCellValue('H1', '存在的异常行为表现');
            $sheet->setCellValue('I1', '发现途径');
            $sheet->setCellValue('J1', '所在单位');
            $sheet->setCellValue('K1', '所属部门');
            $sheet->setCellValue('L1', '所在部门');
            $sheet->setCellValue('M1', '编号');
            $sheet->setCellValue('N1', '学籍状态');
            $sheet->setCellValue('O1', '注册账号');
            $sheet->setCellValue('P1', '所在部门管理员');
            $InterfereUserModel = new InterfereUserModel();
            $where = [
                ['time', 'between', [$start_time, $end_time]],
                ['move_status', '=', 1],
                ['status', '=', 1]
            ];
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', 'in', $param['type_id']];
            }
            $data = $InterfereUserModel->where($where)->with([
                'user' => function ($query) {
                    $query->with(['unitName']);
                },
                'InterfereBehavior' => function ($query) {
                    $query->with(['CrisisBehavior']);
                },
                'OperatorUser' => function ($query) {
                    $query->with(['roleName']);
                },
                'CrisisLevel',
                'CrisisType'
            ])->select()->toArray();
            if (!empty($data)) {
                $department_id = array_column($data, 'department_id');
                $UserService = new UserService($this->app);
                $DepartmentAffiliationAll = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
                $getDepartmentAdminAll = $UserService->getDepartmentAdminAll($department_id);
                foreach ($data as $key => $item) {
                    //异常行为
                    $InterfereBehavior = array_column($item['InterfereBehavior'], 'behavior_name');
                    $behavior_name = implode('、', $InterfereBehavior);
                    //途径
                    $channel_name = match ($item['channel']) {
                        1 => '危机上报手动移入',
                        2 => '任务测评自动加入',
                        3 => '自我测评自动加入',
                        4 => '他人代测自动移入',
                        5 => '无线测评自动移入',
                        6 => '线上咨询手动移入',
                        7 => '线下预约手动移入',
                        8 => '关注人群手动导入',
                        9 => '干预人群手动导入',
                        default => '--',
                    };
                    //学籍状态
                    $item['student_name'] = match ($item['student_status']) {
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    // 设置单元格数据
                    $key = $key + 2;
                    $sheet->setCellValue('A' . $key, $item['user_name']);
                    $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('C' . $key, $item['user_age']);
                    $sheet->setCellValue('D' . $key, $item['status_num']);
                    $sheet->setCellValue('E' . $key, date('Y-m-d H:i:s', $item['status_time']));
                    $sheet->setCellValue('F' . $key, $item['level_name']);
                    $sheet->setCellValue('G' . $key, $item['type_name']);
                    $sheet->setCellValue('H' . $key, $behavior_name);
                    $sheet->setCellValue('I' . $key, $channel_name);
                    $sheet->setCellValue('J' . $key, $item['unit_name']);
                    $sheet->setCellValue('K' . $key, $DepartmentAffiliationAll[$item['department_id']]['ascription_name'] ?? '--');
                    $sheet->setCellValue('L' . $key, $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '--');
                    $sheet->setCellValue('M' . $key, $item['user_number'] ?: '--');
                    $sheet->setCellValue('N' . $key, $item['student_name']);
                    $sheet->setCellValue('O' . $key, $item['username'].' ');
                    $sheet->setCellValue('P' . $key, $getDepartmentAdminAll[$item['department_id']]['user_name'] ?? '--');
                }
            }
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/monthlyReport' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }


    /**
     * 实施干预导出
     * @param array $id 列表id
     * @param int $unit_id 单位id
     * @return string
     */
    public function InterfereUserExport2(array $id, int $unit_id): string
    {
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 设置工作表标题
        $sheet->setTitle('干预人群');
        // 设置单元格数据
        $sheet->setCellValue('A1', '名称');
        $sheet->setCellValue('B1', '性别');
        $sheet->setCellValue('C1', '年龄');
        $sheet->setCellValue('D1', '预检建议优先度');
        $sheet->setCellValue('E1', '干预负责人');
        $sheet->setCellValue('F1', '正在第几次跟进');
        $sheet->setCellValue('G1', '加入干预人群时间');
        $sheet->setCellValue('H1', '危机风险等级');
        $sheet->setCellValue('I1', '疑似问题类型');
        $sheet->setCellValue('J1', '存在的异常行为表现');
        $InterfereUserModel = new InterfereUserModel();
        $data = $InterfereUserModel->where('id', 'in', $id)->with([
            'user' => function ($query) {
                $query->with(['unitName']);
            },
            'InterfereBehavior' => function ($query) {
                $query->with(['CrisisBehavior']);
            },
            'evaluateUser' => function ($query) {
                $query->with(['roleName']);
            },
            'CrisisLevel',
            'CrisisType'
        ])->select()->toArray();
        if (!empty($data)) {
            foreach ($data as $key => $item) {
                $item['evaluate_role_name'] = $item['evaluate_role_name'] ?? "超级管理员";
                //优先级
                $priority_name = match ($item['priority']) {
                    1 => '高度优先',
                    2 => '重度优先',
                    3 => '低度优先',
                    default => '--',
                };
                //异常行为
                $InterfereBehavior = array_column($item['InterfereBehavior'], 'behavior_name');
                $behavior_name = implode('、', $InterfereBehavior);
                // 设置单元格数据
                $key = $key + 2;
                $sheet->setCellValue('A' . $key, $item['user_name']);
                $sheet->setCellValue('B' . $key, $item['user_sex'] == 1 ? '男' : '女');
                $sheet->setCellValue('C' . $key, $item['user_age'] ?: '--');
                $sheet->setCellValue('D' . $key, $priority_name);
                $sheet->setCellValue('E' . $key, $item['evaluate_name'] . '(' . $item['evaluate_role_name'] . ')');
                $sheet->setCellValue('F' . $key, $item['up_num']);
                $sheet->setCellValue('G' . $key, date('Y-m-d H:i:s', $item['time']));
                $sheet->setCellValue('H' . $key, $item['level_name']);
                $sheet->setCellValue('I' . $key, $item['type_name']);
                $sheet->setCellValue('J' . $key, $behavior_name);
            }
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = './export/gy' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname($save_name . $ext);
        folder_build($file_path);
        $writer->save($save_name . $ext);
        return $this->oss($save_name . $ext, $ext, $save_name);
    }


    /**
     * 多方测评档案导出
     * @param int $id
     * @return string
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function multiEvaluation(int $id): string
    {
        $InterfereUserModel = new InterfereUserModel();
        $info = $InterfereUserModel->with(['opinionUser','opinionUser2','opinionUser3'])->find($id);
        if (!$info) return false;
        $opinion = $info['opinion'] + $info['opinion2'] + $info['opinion3'];
        $content = match ($opinion) {
            0 => '3方不同意实施干预',
            1 => '1方同意实施干预，2不同意实施干预',
            2 => '2方同意实施干预，3不同意实施干预',
            3 => '3方同意实施干预',
            default => '--',
        };
        $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/multi_evaluation.docx');
        // 定位并修改内容部分
        $templateProcessor->setValue('evaluate_time', date('Y-m-d H:i:s',$info['evaluate_time']));
        $templateProcessor->setValue('content', $content);
        $templateProcessor->setValue('evaluate_status', $info['evaluate_status']?'确认实施干预':'暂不实施干预');
        $templateProcessor->setValue('opinion_name', $info['opinion_name']);
        $templateProcessor->setValue('opinion2_name', $info['opinion2_name']);
        $templateProcessor->setValue('opinion3_name', $info['opinion3_name']);
        $templateProcessor->setValue('opinion', $info['opinion']);
        $templateProcessor->setValue('opinion_describe', $info['opinion_describe']);
        $templateProcessor->setValue('opinion_sgin', $info['opinion_sgin']);
        $templateProcessor->setValue('opinion2', $info['opinion2']);
        $templateProcessor->setValue('opinion2_describe', $info['opinion2_describe']);
        $templateProcessor->setValue('opinion2_sgin', $info['opinion2_sgin']);
        $templateProcessor->setValue('opinion3', $info['opinion3']);
        $templateProcessor->setValue('opinion3_describe', $info['opinion3_describe']);
        $templateProcessor->setValue('opinion3_sgin', $info['opinion3_sgin']);

        if (!empty($info['opinion_sgin'])) {
            $templateProcessor->setImageValue('opinion_sgin', ['path' => $info['opinion_sgin'], 'width' => 280, 'height' => 124]);
        } else {
            $templateProcessor->setValue('opinion_sgin', ''); // 替换模板中的变量
        }
        if (!empty($info['opinion2_sgin'])) {
            $templateProcessor->setImageValue('opinion2_sgin', ['path' => $info['opinion2_sgin'], 'width' => 280, 'height' => 124]);
        } else {
            $templateProcessor->setValue('opinion2_sgin', ''); // 替换模板中的变量
        }
        if (!empty($info['opinion3_sgin'])) {
            $templateProcessor->setImageValue('opinion3_sgin', ['path' => $info['opinion3_sgin'], 'width' => 280, 'height' => 124]);
        } else {
            $templateProcessor->setValue('opinion3_sgin', ''); // 替换模板中的变量
        }

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/export/multi_evaluation' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs('./public' . $save_name . $ext);
        return $this->oss('./public' . $save_name . $ext, $ext, $save_name);
    }

    /**
     * 预检基本信息
     * @param int $id
     * @param int $unit_id
     * @return false|mixed
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function check_basic_information(int $id,int $unit_id): mixed
    {
        $InterfereUserModel = new InterfereUserModel();
        $info = $InterfereUserModel->with([
            'OperatorUser' => function ($query) {
                $query->with(['roleName']);
            },
            'user' => function ($query) {
                $query->with([
                    'role_name',
                    'unitName',
                    'department' => function ($query) {
                        $query->with([
                            'departmentAdmins' => function ($query) {
                                $query->with(['userName']);
                            }
                        ]);
                    }
                ]);
            },
            'InterfereBehavior' => function ($query) {
                $query->with(['CrisisBehavior']);
            },
            'FollowUser' => function ($query) {
                $query->with([
                    'operator' => function ($query) {
                        $query->with(['roleName']);
                    }
                ]);
            },
            'opinionUser',
            'opinionUser2',
            'opinionUser3',
            'evaluateUser',
            'moveUser',
            'CrisisLevel',
            'CrisisType'
        ])->find($id);
        if (!$info) return false;
        $info = $info->toArray();
        $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/check_basic_information.docx');

        $DepartmentModel = new DepartmentModel();
        $DepartmentLevelModel = new DepartmentLevelModel();
        $UserService = new UserService($this->app);
        $maritalStatus = $UserService->getMaritalStatusSelector();//获取所有婚姻状况
        $politicalOutlook = $UserService->getPoliticalOutlookSelector();//获取所有政治面貌
        $studentStatus = $UserService->getStudentStatusSelector();//获取所有学籍状态

        $departmentInfo = $DepartmentModel->find($info['department_id']);
        $department_name = $UserService->getNotDelDepartmentName($unit_id,$info['department_id']);
        if ($departmentInfo['type'] == 2){
            $levelInfo = $DepartmentLevelModel->find($departmentInfo['mode']);
            $department_mode = $levelInfo['name'];
            $level_rules = json_decode($levelInfo['level_rules'], true);
            $department_level = $level_rules[$departmentInfo['stage']]??'--';
        }else{
            $department_mode = '--';
            $department_level = '--';
        }
        // 定位并修改内容部分
        $templateProcessor->setValue('user_name', $info['user_name']);
        $templateProcessor->setValue('sex', $info['user_sex']==1?'男':'女');
        $templateProcessor->setValue('age', $info['user_age']);
        $templateProcessor->setValue('id_card', $info['id_card']);
        $templateProcessor->setValue('birthday', $info['birthday']);
        $templateProcessor->setValue('phone', $info['phone']);
        $templateProcessor->setValue('native_place', $info['native_place']);
        $templateProcessor->setValue('political_outlook', $politicalOutlook[$info['political_outlook']]['value']??'不限');
        $templateProcessor->setValue('nation', $info['nation']);
        $templateProcessor->setValue('marital_status', $maritalStatus[$info['marital_status']]['value']??'不限');
        $templateProcessor->setValue('address', $info['address']);
        $templateProcessor->setValue('unit_name', $info['unit_name']);
        $templateProcessor->setValue('department_name', $department_name);
        $templateProcessor->setValue('user_number', $info['user_number']);
        $templateProcessor->setValue('department_mode', $department_mode);
        $templateProcessor->setValue('department_level', $department_level);
        $templateProcessor->setValue('student_status', $studentStatus[$info['student_status']]['value']??'不限');

        $InterfereBehavior = array_column($info['InterfereBehavior']??[],'behavior_name');
        //移入诱因说明
        $templateProcessor->setValue('a', $info['describe']);
        //疑似问题类型
        $templateProcessor->setValue('b', $info['type_name']);
        //异常行为表现
        $templateProcessor->setValue('c', implode('、',$InterfereBehavior));
        //疑似风险等级
        $templateProcessor->setValue('d', $info['level_name']);
        // 危险程度表现
        $templateProcessor->setValue('e', $info['level_explain']);

        $follow_channel = match ($info['follow_channel']) {
             1 => '危机上报手动移入',
             2 => '任务测评自动加入',
             3 => '自我测评自动加入',
             4 => '他人代测自动移入',
             5 => '无线测评自动移入',
             6 => '线上咨询手动移入',
             7 => '线下预约手动移入',
             8 => '关注人群手动导入',
             9 => '干预人群手动导入',
            10 => '智慧果手动加入',
            11 => '团体活动手动加入',
            12 => '培训讲座手动加入',
            13 => '心理评估手动加入',
            default => '--'
        };

        $follow_level = match ($info['follow_level']) {
            1 => '轻度',
            2 => '中度',
            3 => '重度',
            4 => '密切',
            default => '--',
        };
        //关注的用户来源
        $templateProcessor->setValue('f', $follow_channel);
        //添加到名单的时间
        $templateProcessor->setValue('g', date('Y-m-d H:i:s',$info['follow_time']));
        //关注期间的负责人
        $templateProcessor->setValue('h', $info['follow_operator_name']);
        //加入关注人群的原因
        $templateProcessor->setValue('i', $info['follow_reason']);
        //当前关注等级设定
        $templateProcessor->setValue('j', $follow_level);

        if (!empty($info['follow_up_content'])) {
            $templateProcessor->cloneBlock('up_content', count($info['follow_up_content']), true, true);
            foreach ($info['follow_up_content'] as $key => $value) {
                $index = $key + 1;
                $templateProcessor->setValue('time#' . $index, $index.'.'.date('Y-m-d',$value['time']));
                $templateProcessor->setValue('title#' . $index, $value['title']);
                $templateProcessor->setValue('content#' . $index, $value['content']);
            }
        }


        // 保存修改后的文档
        $ext = '.docx';
        $save_name = './export/check_basic_information' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname($save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs($save_name . $ext);
        return $this->oss($save_name . $ext, $ext, $save_name);
    }

    /**
     * 智能预检-背景资料
     * @param int $id
     * @return false|mixed
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function user_background_information(int $id): mixed
    {
        $InterfereUserModel = new InterfereUserModel();
        $info = $InterfereUserModel->find($id);
        if (!$info) return false;
        if (empty($info['user_info2'])) return false;
        $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/user_background_information.docx');
        $user_info = json_decode($info['user_info2']??'',true);
        $i = 0;
        while ($i < 60){
            if (empty($user_info)){
                $templateProcessor->setValue('a', '');
                $templateProcessor->setValue('a'.$i, '');
                $i++;
                continue;
            }
            if ($i > 0){
                if($i == 12 && $user_info[$i] == "其他"){
                    $templateProcessor->setValue('a'.$i, '');
                    $i++;
                    $templateProcessor->setValue('a'.$i, $user_info[$i]);
                }else{
                    $templateProcessor->setValue('a'.$i, $user_info[$i]);
                    $i++;
                    $templateProcessor->setValue('a'.$i, ' ');
                }
                if ($i == 14 && !empty($user_info[$i])){
                    $templateProcessor->setValue('a'.$i, $user_info[$i]);
                    $i++;
                    $templateProcessor->setValue('a'.$i, ' ');
                    $i++;
                    $templateProcessor->setValue('a'.$i, ' ');
                }else{
                    $templateProcessor->setValue('a'.$i, ' ');
                    $i++;
                    $templateProcessor->setValue('a'.$i, '日吸烟量：'.$user_info[$i].'只/天');
                    $i++;
                    $templateProcessor->setValue('a'.$i, '累计烟龄：'.$user_info[$i].'年');
                }
                if ($i == 17 && !empty($user_info[$i])){
                    $templateProcessor->setValue('a'.$i, $user_info[$i]);
                    $i++;
                    $templateProcessor->setValue('a'.$i, ' ');
                    $i++;
                    $templateProcessor->setValue('a'.$i, ' ');
                }else{
                    $templateProcessor->setValue('a'.$i, ' ');
                    $i++;
                    $templateProcessor->setValue('a'.$i, '饮酒频率：'.$user_info[$i].'次/年');
                    $i++;
                    $templateProcessor->setValue('a'.$i, '累计酒龄：'.$user_info[$i].'年');
                }
            }else{
                $templateProcessor->setValue('a', $user_info[$i]);
            }
            $i++;
        }

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = './export/user_background_information' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname($save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs($save_name . $ext);
        return $this->oss($save_name . $ext, $ext, $save_name);
    }

    /**
     * 智能预检-问题访谈
     * @param int $id
     * @return false|mixed
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function question_interview(int $id): mixed
    {
        $InterfereUserModel = new InterfereUserModel();
        $info = $InterfereUserModel->find($id);
        if (!$info) return false;
        if (empty($info['issue_log'])) return false;
        $issue_log = json_decode($info['issue_log']??'',true);
        if ($issue_log[0] == 1){
            $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/question_interview.docx');
        }else{
            $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/question_interview2.docx');
        }

        foreach ($issue_log[1] as $key => $value) {
            if ($key > 0){
                $templateProcessor->setValue('a', $value);
            }else{
                $templateProcessor->setValue('a'.$key+2, $value);
            }
        }

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = './export/question_interview' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname($save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs($save_name . $ext);
        return $this->oss($save_name . $ext, $ext, $save_name);
    }

    /**
     * 智能预检-预检结果
     * @param int $id
     * @return false|mixed
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function final_result(int $id): mixed
    {
        $InterfereUserModel = new InterfereUserModel();
        $info = $InterfereUserModel->find($id);
        if (!$info) return false;
        if (empty($info['result'])) return false;
        $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/final_result.docx');

        $result = json_decode($info['result']??'',true);

        //心理危机等级
        $templateProcessor->setValue('a', $info['crisis_level']);
        //建议干预操作
        $templateProcessor->setValue('a2', $info['crisis_operation']);
        //预检完成时间
        $templateProcessor->setValue('a3', $info['move_time'] ? date('Y-m-d H:i:s',$info['move_time']) : '--');

        foreach ($result as $value) {
            switch ($value['key']){
//                case "心理危机等级:":
//                    $templateProcessor->setValue('a', $value['value'][0]['value']);
//                    break;
//                case "建议干预操作:":
//                    $templateProcessor->setValue('a2', $value['value'][0]['value']);
//                    break;
//                case "预检完成时间:":
//                    $templateProcessor->setValue('a3', $value['value'][0]['value']);
//                    break;
                case "危机来源:":
                    $templateProcessor->setValue('a4', $value['value'][0]['value']??'--');
                    break;
                case "用户现状:":
                    $templateProcessor->setValue('a5', $value['value'][0]['value']??'--');
                    $templateProcessor->setValue('a6', $value['value'][1]['value']??'--');
                    break;
                case "现病史描述:":
                    $templateProcessor->setValue('a7', $value['value'][0]['value']??'--');
                    break;
                case "过往病史情况:":
                    $templateProcessor->setValue('a8', $value['value'][0]['value']??'--');
                    break;
                case "家庭病史情况:":
                    $templateProcessor->setValue('a9', $value['value'][0]['value']??'--');
                    break;
                case "访谈问题情况:":
                    $templateProcessor->setValue('a10', $value['value'][0]['value']??'--');
                    break;
            }
        }

        $level = match ($info['level']){
            1 => '一级',
            2 => '二级',
            3 => '三级',
            4 => '四级',
            5 => '五级',
        };
        //优先级【1高度优先，2重度优先，3低度优先】
        $priority = match ($info['level']){
            1 => '高度优先',
            2 => '重度优先',
            3 => '低度优先',
        };
        //状态【0移入干预预检中，1移入成功，2不移入】
        $move_status = match ($info['move_status']){
            1 => '移入多方评估，启动危机干预',
            2 => '无需移入多方评估，继续保持关注',
            default => '预检中'
        };
        $templateProcessor->setValue('a11', $level);
        $templateProcessor->setValue('a12', $priority);
        $templateProcessor->setValue('a13', $move_status);

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = './export/final_result' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname($save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs($save_name . $ext);
        return $this->oss($save_name . $ext, $ext, $save_name);
    }

}